/*
 * @Author: 橘子
 * @Date: 2022-11-26 11:53:16
 * @Project_description: 基于db模块的上层封装
 * @Description: 代码是我抄的，不会也是真的
 */
import { dbGet, dbSet } from './util.db'
import cookies from './util.cookies'
import store from '@/store'

let db = {}

/**
 * @desc:  输入key获取当前不然为空，没有key就获取全部
 * @param {*} key sysOrg.orgName 支持链式调用
 * @return {*}
 * @Author: 橘子
 */
db._getUser = function(key) {
  let base = {
    dbName: 'sys',
    path: 'user.info' + (key ? '.' + key : ''),
    user: true,
  }
  return dbGet(base)
}

/**
 * @desc:  设置用户信息
 * @param {*} key 支持key 支持链式调用
 * @param {*} value   要设置的值
 * @return {*}
 * @Author: 橘子
 */
db._setUser = function(key, value) {
  let base = {
    dbName: 'sys',
    path: 'user.info' + (key ? '.' + key : ''),
    value: value,
    user: true,
  }

  store.dispatch('d2admin/user/edit')
  dbSet(base)
}

/**
 * @desc:  设置公共存储
 * @param {*} key key
 * @param {*} value
 * @return {*}
 * @Author: 橘子
 */
db._setGlobalDb = function(key, value) {
  let base = {
    dbName: 'database',
    path: key,
    value: value,
    user: false,
  }
  dbSet(base)
}

/**
 * @desc:  获取公共存储
 * @param {*} key
 * @return {*}
 * @Author: 橘子
 */
db._getGlobalDb = function(key) {
  let base = {
    dbName: 'database',
    path: key,
    user: false,
  }
  return dbGet(base)
}

/**
 * @desc:  获取私有存储
 * @param {*} key
 * @return {*}
 * @Author: 橘子
 */
db._getuserDb = function(key) {
  let base = {
    dbName: 'database',
    path: key,
    user: true,
  }
  return dbGet(base)
}

/**
 * @desc:  设置私有存储
 * @param {*} key
 * @param {*} value
 * @return {*}
 * @Author: 橘子
 */
db._setUserDb = function(key, value) {
  let base = {
    dbName: 'database',
    path: key,
    value: value,
    user: true,
  }
  dbSet(base)
}

/**
 * @desc: 清除用户所有信息
 * @return {*}
 * @Author: 橘子
 */
db._clearUser = function() {
  dbSet({ dbName: 'database', path: '', value: {}, user: true })
  dbSet({ dbName: 'sys', path: 'user.info', value: {}, user: true })
  const data = cookies.getAll()
  //获取所有的key
  let keys = Object.keys(data)
  //清除
  keys.forEach((key) => {
    let v = key.split('-')
    cookies.remove(v[v.length - 1])
  })
}

/**
 * @desc: 清空所有公共存储
 * @return {*}
 * @Author: 橘子
 */
db._clearGlobal = function() {
  dbSet({ dbName: 'database', path: '', value: {}, user: false })
}

export default db
